#include "tcpserverdispatcher.h"
#include <memory>

TcpServerDispatcher::TcpServerDispatcher(TcpServerConnectionFactory* pFactory, 
            ThreadPool& threadPool):
    m_stopped(false),
    m_pConnectionFactory(pFactory),
    m_threadPool(threadPool)
{
    m_thread.start(*this);
}

TcpServerDispatcher::~TcpServerDispatcher()
{
}

void TcpServerDispatcher::run()
{
    TcpServerConnection* pConn = NULL;
    map<int,TcpServerConnection*>::iterator it;
    for (;;)
    {
        pConn = NULL;
        if (m_stopped)
            break;
        {
            ScopedMutex lock(&m_mutex);
            if (!m_queue.empty())
            {
                it = m_queue.begin();
                pConn = it->second;
                m_queue.erase(it);
            }
        }
        if (pConn)
            pConn->run();
    }
}

bool TcpServerDispatcher::enqueue(int fd)
{
    if (fd < 0)
        return false;

    ScopedMutex lock(&m_mutex);
    map<int,TcpServerConnection*>::iterator it = m_queue.find(fd);
    if ( it == m_queue.end() )
    {
        TcpServerConnection* pConn = m_pConnectionFactory->createConnection(fd);
        m_queue[fd] = pConn;
    }
    
    return true;
}

void TcpServerDispatcher::stop()
{
    m_stopped = true;
}




